"""
Case Type   : 基础功能
Case Name   : 存在多个一一对应发布不同内容的发布订阅，订阅方式不一样
Create At   : 2022/11/09
Owner       : opentestcase026
Description :
    1.分表两个集群创建3张表
    2.创建3个发布，发布内容不同
    3.二进制及非二进制传输方式订阅
    4.发布端表中插入数据
    5.查询订阅端数据是否同步
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.数据同步
    6.成功
History     :
"""

import os
import time
import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.com_pub = Common()
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.tb_name = ['t_pubsub_0205_1', 't_pubsub_0205_2',
                        't_pubsub_0205_3']
        self.subname = [('sub_pubsub_0205_1', 'true'),
                        ('sub_pubsub_0205_2', 'false'),
                        ('sub_pubsub_0205_3', 'true')]
        self.pubname = ['pub_pubsub_0205_1', 'pub_pubsub_0205_2',
                        'pub_pubsub_0205_3']
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
                              f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
                              f'-W {self.pri_userdb_sub.db_password}'
        self.wal_level = self.com_pub.show_param("wal_level")
        text = '-----查询集群状态，配置白名单，发布端设置wal_level=logical-----'
        self.log.info(text)
        self.log.info('-----发布端状态-----')
        status = self.commsh_pub.get_db_cluster_status('detail')
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        self.log.info('-----订阅端状态-----')
        status = self.commsh_sub.get_db_cluster_status(
            'detail', env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host replication {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32  sha256')
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'发布端配置白名单失败:{text}')
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, f'设置wal_level失败:{text}')
            restart_res = self.commsh_pub.restart_db_cluster()
            self.assertTrue(restart_res, f'重启数据库失败:{text}')
        guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host replication {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32 sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'订阅端配置白名单失败:{text}')

    def test_pub_sub(self):
        text = "-----step1:两个集群创建表;expect:成功-----"
        self.log.info(text)
        create_tb = \
            f'''drop table if exists {self.tb_name[0]}, {self.tb_name[1]}, 
            {self.tb_name[2]} cascade;
            create table {self.tb_name[0]}(i int primary key, t text);
            create table {self.tb_name[1]}(i int primary key, t text);
            create table {self.tb_name[2]}(c_id integer, 
            c_date date primary key, c_info varchar(20) not null) 
            partition by range(c_date) interval('2 day')(
            partition p1 values less than ('2021-06-01 00:00:00'),
            partition p2 values less than ('2021-06-03 00:00:00'),
            partition p3 values less than ('2021-06-05 00:00:00'),
            partition p4 values less than ('2021-06-07 00:00:00'),
            partition p5 values less than ('2021-06-09 00:00:00'));'''
        pub_res = self.commsh_pub.execut_db_sql(create_tb,
                                                sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertEqual(pub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         6, f'执行失败:{text}')
        sub_res = self.commsh_sub.execut_db_sql(
            create_tb, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertEqual(sub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         6, f'执行失败:{text}')

        text = "-----step2:创建3个发布，发布内容不同;expect:成功-----"
        self.log.info(text)
        for pub, table in zip(self.pubname, self.tb_name):
            create_pub = f"drop publication if exists {pub};" \
                         f"create publication {pub} for table {table};"
            pub_res = self.commsh_pub.execut_db_sql(
                create_pub, sql_type=self.user_param_pub)
            self.log.info(pub_res)
            self.assertIn(self.constant.create_pub_succ_msg, pub_res,
                          f'执行失败:{text}')

        text = "-----step3:创建二进制及非二进制传输方式订阅;expect:成功-----"
        self.log.info(text)
        guc_res = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success, guc_res,
                      f'执行失败:{text}')
        for pub, sub in zip(self.pubname, self.subname):
            create_sub = \
                f"drop subscription if exists {sub[0]};" \
                f"create subscription {sub[0]} connection " \
                f"'host={self.pri_userdb_pub.db_host} " \
                f"port={self.port} user={self.pri_userdb_pub.db_user} " \
                f"dbname={self.pri_userdb_pub.db_name} " \
                f"password={self.pri_userdb_pub.ssh_password}' " \
                f"publication {pub} with (binary={sub[1]});"
            sub_res = self.commsh_sub.execut_db_sql(
                create_sub, self.user_param_sub,
                env_path=macro.DB_ENV_PATH_REMOTE1)
            self.log.info(sub_res)
            self.assertIn(self.constant.drop_sub_succ_msg, sub_res,
                          f'执行失败:{text}')
            self.assertIn(self.constant.create_sub_succ_msg, sub_res,
                          f'执行失败:{text}')

        text = "-----step4:发布端表中插入数据;expect:成功-----"
        self.log.info(text)
        sql_cmd = f"insert into {self.tb_name[0]} values(1, 'first%');" \
                  f"insert into {self.tb_name[1]} values(1, 'first%');" \
                  f"insert into {self.tb_name[2]} values(" \
                  f"1, '2021-05-30 00:00:00', '1-1');"
        pub_result = self.commsh_pub.execut_db_sql(sql_cmd,
                                                   sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertEqual(pub_result.count(self.constant.INSERT_SUCCESS_MSG), 3,
                         f'执行失败:{text}')

        text = "-----step5:订阅端查询数据是否同步;expect:数据同步-----"
        self.log.info(text)
        time.sleep(6)
        sql_select = f"select * from {self.tb_name[0]};" \
                     f"select * from {self.tb_name[1]};" \
                     f"select * from {self.tb_name[2]};"
        select_res = self.commsh_sub.execut_db_sql(
            sql_select, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(select_res)
        self.assertEqual(select_res.count('first%'), 2, f'执行失败:{text}')
        self.assertIn('2021-05-30 00:00:00', select_res, f'执行失败:{text}')

    def tearDown(self):
        text = "-----step6:清理环境;expect:成功-----"
        self.log.info(text)
        drop_sub_res = []
        drop_pub_res = []
        for subname in self.subname:
            drop_sub = self.commsh_sub.execut_db_sql(
                f"drop subscription if exists {subname[0]};",
                self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
            self.log.info(drop_sub)
            drop_sub_res.append(drop_sub)
        for pubname in self.pubname:
            drop_pub = self.commsh_pub.execut_db_sql(
                f"drop publication if exists {pubname};",
                sql_type=self.user_param_pub)
            self.log.info(drop_pub)
            drop_pub_res.append(drop_pub)
        sql_cmd = f"drop table if exists {self.tb_name[0]}, " \
                  f"{self.tb_name[1]},{self.tb_name[2]} cascade;"
        pub_droptb = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(pub_droptb)
        sub_droptb = self.commsh_sub.execut_db_sql(
            sql_cmd, self.user_param_sub, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_droptb)
        guc_res1 = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host replication {self.pri_userdb_sub.db_user} '
            f'{self.pri_userdb_sub.db_host}/32')
        self.log.info(guc_res1)
        guc_res2 = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host replication  {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res2)
        res_wal = self.commsh_pub.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'wal_level={self.wal_level}')
        self.log.info(res_wal)
        pub_restartdb = self.commsh_pub.restart_db_cluster()
        self.assertTrue(pub_restartdb, f'发布端重启数据库失败:{text}')
        for res in drop_sub_res:
            self.assertIn(self.constant.drop_sub_succ_msg, res,
                          f'删除订阅失败:{text}')
        self.assertEqual(drop_pub_res.count("DROP PUBLICATION"), 3,
                         f'删除发布失败:{text}')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, pub_droptb,
                      f'发布端删除表失败:{text}')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, sub_droptb,
                      f'订阅端删除表失败:{text}')
        self.assertTrue(guc_res1, f'发布端删除白名单失败:{text}')
        self.assertTrue(guc_res2, f'订阅端删除白名单失败:{text}')
        self.assertTrue(res_wal, f'发布端恢复wal_level参数失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
